<template>
  <div class="solution-list">
    <div class="solution-header">
      <h3>题解列表</h3>
      <a-tooltip :content="buttonTooltip">
        <a-button type="primary" :disabled="!isProblemPassed" @click="openPublishModal">
          <template #icon><icon-plus /></template>
          发布题解
        </a-button>
      </a-tooltip>
    </div>

    <a-spin :loading="loading" tip="加载中..." style="width: 100%;">
      <a-empty v-if="!loading && solutions.length === 0" description="暂无题解" />
      <div v-else class="solution-cards">
        <a-card 
          v-for="solution in solutions" 
          :key="solution.id" 
          class="solution-card"
          :title="solution.title" 
          :bordered="false"
          hoverable
        >
          <template #extra>
            <span class="solution-time">{{ formatTime(solution.createTime) }}</span>
          </template>
          <div class="solution-meta">
            <div class="solution-author">
              <a-avatar :size="28" :image-url="solution.avatar || undefined">
                {{ solution.avatar ? '' : solution.username.charAt(0).toUpperCase() }}
              </a-avatar>
              <span class="author-name">{{ solution.username }}</span>
            </div>
          </div>
          <div class="solution-content-preview">
            <MarkdownViewer :value="getPreviewContent(solution.content)" />
          </div>
          <template #actions>
            <a-space>
              <a-button type="text" @click="viewSolutionDetail(solution)">
                <template #icon><icon-eye /></template>
                查看详情
              </a-button>
            </a-space>
          </template>
        </a-card>
      </div>

      <div class="pagination-container" v-if="total > 0">
        <a-pagination 
          :total="total" 
          :current="current" 
          :page-size="pageSize"
          @change="handlePageChange" 
        />
      </div>
    </a-spin>

    <!-- 题解详情抽屉 -->
    <a-drawer
      :visible="drawerVisible"
      @cancel="closeDrawer"
      @ok="closeDrawer"
      :width="700"
      :footer="false"
      unmountOnClose
    >
      <template #title>
        <span v-if="currentSolution">{{ currentSolution.title }}</span>
      </template>
      <div class="solution-detail" v-if="currentSolution">
        <div class="solution-author-info">
          <a-avatar :size="32" :image-url="currentSolution.avatar || undefined">
            {{ currentSolution.avatar ? '' : currentSolution.username.charAt(0).toUpperCase() }}
          </a-avatar>
          <div class="author-detail">
            <div class="author-name">{{ currentSolution.username }}</div>
            <div class="publish-time">{{ formatTime(currentSolution.createTime) }}</div>
          </div>
        </div>

        <a-divider />

        <div class="solution-full-content">
          <MarkdownViewer :value="currentSolution.content" />
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { IconEye, IconPlus } from '@arco-design/web-vue/es/icon'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import MarkdownViewer from '@/components/MarkdownViewer.vue'
import { checkProblemPassApi } from '@/api/problem/problem'

interface Solution {
  id: string
  problemId: string
  userId: string
  username: string
  avatar: string
  title: string
  content: string
  createTime: string
}

interface Props {
  problemId: number
}

const props = defineProps<Props>()
const emit = defineEmits(['load-solutions'])

// 状态变量
const loading = ref(false)
const solutions = ref<Solution[]>([])
const total = ref(0)
const current = ref(1)
const pageSize = ref(10)
const drawerVisible = ref(false)
const currentSolution = ref<Solution | null>(null)
const isProblemPassed = ref(false)
const buttonTooltip = ref('')

const router = useRouter()

// 格式化时间显示
const formatTime = (time: string) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 获取预览内容，限制长度
const getPreviewContent = (content: string) => {
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}

// 查看题解详情
const viewSolutionDetail = (solution: Solution) => {
  currentSolution.value = solution
  drawerVisible.value = true
}

// 关闭详情抽屉
const closeDrawer = () => {
  drawerVisible.value = false
}

// 获取题解列表
const fetchSolutions = async () => {
  loading.value = true
  try {
    // 通过父组件处理加载数据
    emit('load-solutions', {
      current: current.value,
      size: pageSize.value,
      problemId: props.problemId
    })
    // 注意：updateSolutionData方法会在父组件回调中被调用，那里会将loading设置为false
  } catch (error) {
    console.error('获取题解列表失败', error)
    loading.value = false
  }

  checkProblemPassed()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  current.value = page
  fetchSolutions()
}

// 更新题解数据
const updateSolutionData = (data: { records: Solution[], total: number }) => {
  solutions.value = data.records
  total.value = Number(data.total)
  loading.value = false
}

// 暴露方法给父组件
defineExpose({
  fetchSolutions,
  updateSolutionData
})

// 打开发布题解页面
const openPublishModal = () => {
  if (!isProblemPassed.value) {
    Message.warning('您需要先通过此题后才能发布题解')
    return
  }
  
  // 跳转到发布题解页面，并传递题目ID
  router.push({
    path: '/problem/solution/publish',
    query: {
      problemId: props.problemId.toString()
    }
  })
}

// 检查题目是否通过
const checkProblemPassed = async () => {
  try {
    const res = await checkProblemPassApi({ problemId: props.problemId })
    if (res && res.code === 0) {
      isProblemPassed.value = !!res.data
      updateButtonTooltip()
    }
  } catch (error) {
    console.error('检查题目通过状态失败', error)
    isProblemPassed.value = false
    updateButtonTooltip()
  }
}

// 更新按钮提示
const updateButtonTooltip = () => {
  buttonTooltip.value = isProblemPassed.value 
    ? '发布您的解题思路' 
    : '您需要先通过此题后才能发布题解'
}
</script>

<style scoped>
.solution-list {
  width: 100%;
  height: 100%;
}

.solution-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 8px;
}

.solution-header h3 {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-1);
  margin: 0;
}

.solution-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.solution-card {
  margin-bottom: 16px;
  border-bottom: 1px solid var(--color-border);
}

.solution-card:last-child {
  border-bottom: none;
}

.solution-meta {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.solution-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-size: 14px;
  color: var(--color-text-2);
}

.solution-time {
  font-size: 13px;
  color: var(--color-text-3);
}

.solution-content-preview {
  max-height: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  position: relative;
}

.solution-content-preview::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  height: 30px;
  width: 100%;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0), var(--color-bg-2));
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 题解详情样式 */
.solution-detail {
  padding: 0 16px;
}

.solution-author-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.author-detail {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  font-size: 15px;
  color: var(--color-text-1);
}

.publish-time {
  font-size: 13px;
  color: var(--color-text-3);
}

.solution-full-content {
  padding: 16px 0;
}
</style> 